//
//  NearbyShopViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/10/15.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "NearbyShopViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "AnnotationViewForMallHome.h"
#import "ShopLocationInfo.h"
#import "ShopListTableViewCell.h"
#import "ShopHomeViewController.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "ErrorInfoUtility.h"

@interface NearbyShopViewController ()<UISearchBarDelegate, MAMapViewDelegate, CLLocationManagerDelegate, AMapLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource, AMapSearchDelegate>

@property (strong, nonatomic) UIView *headBgView;
//@property (nonatomic,strong) AMapLocationManager * locationManager;
@property (nonatomic,strong) CLLocationManager * locationManager;
@property (strong ,nonatomic) CLGeocoder *geocoder;
@property (strong, nonatomic) MAMapView *mapView;
@property (assign, nonatomic) CLLocationDegrees latitude;
@property (assign, nonatomic) CLLocationDegrees longitude;
@property (strong, nonatomic) NSMutableArray<MAPointAnnotation *> *annotationArr;
@property (strong, nonatomic) NSMutableArray<ShopLocationInfo *> *shopInfoArr;
@property (strong, nonatomic) NSString *keyword;
@property (strong, nonatomic) UILabel *shopCountLabel;
@property (strong, nonatomic) UITableView *shopListView;
@property (strong, nonatomic) UIView *cellMaskView;

//高德地图搜索，此处拿来进行地理编码
@property (nonatomic, strong) AMapSearchAPI *search;


@property (assign, nonatomic) ShopListTableViewCell *lastCell;

@end

@implementation NearbyShopViewController

- (void)viewDidAppear:(BOOL)animated
{
	[self getLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
	[center addObserver:self selector:@selector(bottomViewScrollToIndex:) name:@"BottomTableScrollToIndex" object:nil];
	[self createUI];
}

- (void)createUI {
	
	/*
	_headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
	_headBgView.backgroundColor = UIMainColorRGB;
	[self.view addSubview:_headBgView];
	 */
	self.view.backgroundColor = UISeparatedColorRGB;
	
	UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(100, 0, SCREEN_WIDTH-130, 30)];
	searchBar.placeholder = @"请输入要查询的商家…";
	searchBar.backgroundImage = IMAGE(@"clearImage");
	searchBar.layer.cornerRadius = searchBar.height/2;
	searchBar.layer.masksToBounds = YES;
	searchBar.keyboardType = UIKeyboardTypeDefault;
	searchBar.delegate = self;
	searchBar.searchBarStyle = UISearchBarStyleDefault;
	
	UIView *searchTextField = [searchBar valueForKey:@"_searchField"];
	searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
	self.navigationItem.titleView = searchBar;
	
	[AMapServices sharedServices].enableHTTPS = YES;
	_mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
	_mapView.showsUserLocation = YES;
	_mapView.delegate = self;
	_mapView.userTrackingMode = MAUserTrackingModeFollow;
	_mapView.zoomLevel = 16;
	[self.view addSubview:_mapView];
	self.search = [[AMapSearchAPI alloc] init];
	self.search.delegate = self;
	
	UIView *shopView = [[UIView alloc] initWithFrame:CGRectMake(10, SCREEN_HEIGHT*0.55, SCREEN_WIDTH-20, SCREEN_HEIGHT*0.45)];
	[self.view addSubview:shopView];
	UIView *shopCountView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, shopView.width, 50)];
	shopCountView.backgroundColor = kWhiteColor;
	[shopView addSubview:shopCountView];
	_shopCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(shopCountView.width/2-100, 10, 200, 30)];
	_shopCountLabel.textAlignment = NSTextAlignmentCenter;
	[shopCountView addSubview:_shopCountLabel];
	
	//高度方面不知为何如果设置了刚刚好为shopView-shopCountView的话会拉不到最后一个cell
	_shopListView = [[UITableView alloc] initWithFrame:CGRectMake(0, shopCountView.y+shopCountView.height, shopView.width, shopView.height-130)];
	_shopListView.delegate = self;
	_shopListView.dataSource = self;
	[_shopListView registerNib:[UINib nibWithNibName:@"ShopListTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
	[shopView addSubview:_shopListView];
	
	UIButton *myPositionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	myPositionBtn.frame = CGRectMake(SCREEN_WIDTH-50, shopView.y-50, 30, 30);
	[myPositionBtn setBackgroundImage:IMAGE(@"lo_icon_map") forState:UIControlStateNormal];
	[myPositionBtn addActionWithblock:^{
		self.keyword = @"";
		searchBar.text = @"";
		[self.locationManager startUpdatingLocation];
	}];
	[self.view addSubview:myPositionBtn];
}

- (void)getAnnotation {
	[_mapView removeAnnotations:self.annotationArr];
	[self.annotationArr removeAllObjects];
	if (!self.keyword) {
		self.keyword = @"";
	}
	NSDictionary *dict = @{
						   @"lat":[NSString stringWithFormat:@"%lf", self.latitude],
						   @"lng":[NSString stringWithFormat:@"%lf", self.longitude],
						   @"keyword":self.keyword
						   };
	NSLog(@"dict = %@", dict);
	[[NetworkTool sharedTool] requestWithName:@"获取商家信息" URLString:APIFindShop parameters:dict method:@"POST" callBack:^(id responseObject) {
		NSArray *arr = responseObject[@"data"];
		//获取信息填充model集合
		[self.shopInfoArr removeAllObjects];
		for (NSDictionary *dict in arr){
			ShopLocationInfo *model = [[ShopLocationInfo alloc] init];
			[model setValuesForKeysWithDictionary:dict];
			[self.shopInfoArr addObject:model];
		}
		[self.shopListView reloadData];
		//根据model集合信息创造annotation集合
		for (ShopLocationInfo *model in self.shopInfoArr){
			MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
			pointAnnotation.coordinate = CLLocationCoordinate2DMake(model.lat, model.lng);
			NSLog(@"%lf, %lf", pointAnnotation.coordinate.latitude, pointAnnotation.coordinate.longitude);
			pointAnnotation.title = model.shop_name;
			pointAnnotation.subtitle = model.sign;
			[self.annotationArr addObject:pointAnnotation];
			[_mapView addAnnotation:pointAnnotation];
		}
		[self.mapView showAnnotations:self.annotationArr animated:YES];
		self.shopCountLabel.text = [NSString stringWithFormat:@"为您搜索到%ld家商家",self.shopInfoArr.count];
		if (self.shopInfoArr.count == 0) {
			MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
			hud.mode = MBProgressHUDModeText;
			hud.label.text = @"抱歉，没有找到相关信息";
			[hud hideAnimated:YES afterDelay:1.0];
            if (![NSString isEmpty:self.keyword]) {
                AMapGeocodeSearchRequest *geo = [[AMapGeocodeSearchRequest alloc] init];
                geo.address = self.keyword;
                [self.search AMapGeocodeSearch:geo];
            }
            else {
                CLLocationCoordinate2D location = CLLocationCoordinate2DMake(self.latitude, self.longitude);
                [self.mapView setCenterCoordinate:location animated:YES];
            }
		}
		
	}];
}

#pragma mark - 懒加载

- (NSMutableArray<MAPointAnnotation *> *)annotationArr
{
	if (!_annotationArr) {
		_annotationArr = [[NSMutableArray alloc] init];
	}
	return _annotationArr;
}

- (NSMutableArray<ShopLocationInfo *> *)shopInfoArr
{
	if (!_shopInfoArr) {
		_shopInfoArr = [[NSMutableArray alloc] init];
	}
	return _shopInfoArr;
}

#pragma mark - 定位
- (void)getLocation {
	if([CLLocationManager locationServicesEnabled])
	{
		NSLog(@"I am here 123125346465576");
		[self.locationManager requestWhenInUseAuthorization];
		[self.locationManager startUpdatingLocation];
	}
	else {
		[self presentViewController:[LZCTools alertMessage:@"无法定位，请检查是否已为本应用开启定位权限"] animated:YES completion:nil];
	}
}

- (CLLocationManager *)locationManager
{
	if (!_locationManager) {
		_locationManager = [[CLLocationManager alloc] init];
		_locationManager.delegate = self;
		_locationManager.distanceFilter = kCLDistanceFilterNone;
		_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	}
	return _locationManager;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
	CLLocation *loc = [locations firstObject];
	
	//维度：loc.coordinate.latitude
	//经度：loc.coordinate.longitude
	NSLog(@"纬度=%f，经度=%f",loc.coordinate.latitude,loc.coordinate.longitude);
	self.latitude = loc.coordinate.latitude;
	self.longitude = loc.coordinate.longitude;
	[self getAnnotation];
	[self.geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
		if (placemarks.count > 0){
			CLPlacemark *placemark = [placemarks objectAtIndex:0];
			NSLog(@"address is %@", placemark);
			//获取当前城市
			NSString *city = placemark.locality;
			NSString *area = placemark.subLocality;
			NSLog(@"%@%@", city,area);
			if (!city) {
				//注意：四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
				city = placemark.administrativeArea;
			}
		}
		else if (error == nil && [placemarks count] == 0) {
			NSLog(@"没有结果返回.");
		}
		else if (error != nil)  {
			NSLog(@"An error occurred = %@", error);
		}
	}];
	[manager stopUpdatingLocation];
}

- (CLGeocoder *)geocoder
{
	if (!_geocoder) {
		_geocoder = [[CLGeocoder alloc] init];
	}
	return _geocoder;
}

/*高德地图的获取当前经纬度不知为何速度很慢，干脆直接用Apple自带的（明明也是官方合作商为什么。。）
- (AMapLocationManager *)locationManager{
	if (!_locationManager) {
		_locationManager = [[AMapLocationManager alloc]init];
	}
	return _locationManager;
}
- (void)location{
	self.locationManager.delegate = self;
	//高精度定位
	// 带逆地理信息的一次定位(返回坐标和地址信息)
	[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
	//  定位超时时间,最低2s,此处设置为10s
	self.locationManager.locationTimeout = 10;
	//  逆地理请求超时时间,最低2s,此处设置为10s
	self.locationManager.reGeocodeTimeout = 10;
	//获得返回的地址
	[self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
		if (error)
		{
			NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
			if (error.code == AMapLocationErrorLocateFailed)
			{
				return;
			}
		}
		NSLog(@"location:%@", location);
		//得到定位的经纬度
		CLLocationDegrees latitude = location.coordinate.latitude;
		CLLocationDegrees longitude = location.coordinate.longitude;
		NSLog(@"经度%f:",longitude);
		NSLog(@"纬度%f:",latitude);
		if (regeocode)
		{
			NSLog(@"reGeocode:%@", regeocode);
			NSLog(@"reGeocode.cityName:%@", regeocode.city);
		}
		self.latitude = latitude;
		self.longitude = longitude;
		[self getAnnotation];
	}];
}
*/

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
	if ([annotation isKindOfClass:[MAPointAnnotation class]])
	{
		static NSString *reuseIndetifier = @"annotationReuseIndetifier";
		AnnotationViewForMallHome *annotationView = (AnnotationViewForMallHome *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
		if (annotationView == nil)
		{
			annotationView = [[AnnotationViewForMallHome alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
		}
		//annotationView.image = [UIImage imageNamed:@"restaurant"];
		
		annotationView.modelArr = self.shopInfoArr;
		
		// 设置为NO，用以调用自定义的calloutView
		annotationView.canShowCallout = NO;
		
		// 设置中心点偏移，使得标注底部中间点成为经纬度对应点
		annotationView.centerOffset = CGPointMake(0, -18);
		return annotationView;
	}
	return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	ShopListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
	ShopLocationInfo *model = self.shopInfoArr[indexPath.row];
	cell.model = model;
	[cell.jumpToShopBtn addActionWithblock:^{
		ShopHomeViewController *vc = [[ShopHomeViewController alloc] init];
		vc.shopId = self.shopInfoArr[indexPath.row].shop_id;
		NSLog(@"shopid is %@", vc.shopId);
		[self.navigationController pushViewController:vc animated:YES];
	}];
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	if (model.isScrolled) {
		cell.maskView.hidden = NO;
	}
	else {
		cell.maskView.hidden = YES;
	}
	return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return self.shopInfoArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	tableView.rowHeight = UITableViewAutomaticDimension;
	return tableView.rowHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	//[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//商家搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	self.keyword = searchBar.text;
	[searchBar resignFirstResponder];
	[self getAnnotation];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
	return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
	NSLog(@"开始输入搜索内容");
	
	// 取消字体颜色？
	searchBar.showsCancelButton = YES;
	[searchBar setShowsCancelButton:YES animated:YES];
	UITextField *searchBarTextField = nil;
	NSArray *views = ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) ? searchBar.subviews : [[searchBar.subviews objectAtIndex:0] subviews];
	for (UIView *subview in views)
	{
		if ([subview isKindOfClass:[UITextField class]])
		{
			searchBarTextField = (UITextField *)subview;
			break;
			
		}
	}
	searchBarTextField.enablesReturnKeyAutomatically = NO;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
	NSLog(@"输入搜索完毕");
	
	[searchBar setShowsCancelButton:NO animated:YES];
	[searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
	NSLog(@"取消搜索");
	
	[searchBar setShowsCancelButton:NO animated:YES];
	[searchBar resignFirstResponder];
}

- (void)bottomViewScrollToIndex:(NSNotification *)notification{
	[self.shopListView reloadData];
	dispatch_async(dispatch_get_main_queue(), ^{
		//刷新完成
		NSInteger index = [notification.userInfo[@"index"] integerValue];
		NSLog(@"index is %ld", index);
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
		for(int i = 0; i<self.shopInfoArr.count; i++) {
			ShopLocationInfo *model = self.shopInfoArr[i];
			if (i == index) {
				model.isScrolled = YES;
			}
			else {
				model.isScrolled = NO;
			}
		}
		
		if (self.shopInfoArr.count > index &&
			[self.shopListView numberOfRowsInSection:1] > index) {
			[self.shopListView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
		}
	});
	
}

//高德地图地理编码搜索回调
#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
	NSLog(@"Error: %@ - %@", error, [ErrorInfoUtility errorDescriptionWithCode:error.code]);
}

- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response {
	
	//拿到返回结果的第一个
	if (response.count > 0) {
		AMapGeocode *geo = response.geocodes[0];
		CLLocationCoordinate2D location = CLLocationCoordinate2DMake(geo.location.latitude, geo.location.longitude);
		[self.mapView setCenterCoordinate:location animated:YES];
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
